// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: hyuan

#pragma once

#include <memory>
#include <string>
#include <unordered_map>

#include "coin2/exchange/base/order/order.h"
#include "coin2/exchange/kucoin/api_util/auth_key.h"
#include "coin2/exchange/kucoin/api_util/rate_tracker.h"
#include "coin2/exchange/order/kucoin.pb.h"

enum KucoinOrderSubTopicId : int { UNKNOWN = -1, REST_BULLET = 10000 };

class KucoinNativePrivateClient : public coin2::exchange::base::order::NativePrivateClient {
 public:
  using RestParams = coin2::exchange::order::KucoinRestParams;
  using NativeClientConfig = coin2::exchange::order::OrderConnectionConfig;
  using RestQueryProto = coin2::exchange::base::order::RestQueryProto;
  using ActionType = coin2::exchange::base::order::NativePrivateClient::ActionType;
  using QueryType = coin2::exchange::kucoin::api_util::QueryType;
  using KucoinRateTracker = coin2::exchange::kucoin::api_util::KucoinRateTracker;
  using AsioHttpContextList = std::list<std::shared_ptr<AsioHttpContext>>;

 public:
  explicit KucoinNativePrivateClient(
      const MarketExchangeApi& mea,
      const NativeClientConfig& config);

  std::shared_ptr<AsioHttpContext> QueryAccountBalance();
  std::shared_ptr<AsioHttpContext> QueryAccountCrossBalance();
  std::shared_ptr<AsioHttpContext> QueryOpenOrders(const RestParams& params);
  std::shared_ptr<AsioHttpContext> QueryHistoryOrders(const RestParams& params);
  std::shared_ptr<AsioHttpContext> QueryFills(const RestParams& params);
  std::shared_ptr<AsioHttpContext> QueryBullet();

  std::shared_ptr<AsioHttpContext> PlaceOrder(const RestParams& params);
  std::shared_ptr<AsioHttpContext> CancelOrder(const RestParams& params);
  std::shared_ptr<AsioHttpContext> PlaceOrderNorm(const OrderExecution&) override;
  std::shared_ptr<AsioHttpContext> CancelOrderNorm(const OrderExecution&) override;
  std::shared_ptr<AsioHttpContext> SubmitOrderExecution(const OrderExecutionProto& order) override;
  std::shared_ptr<AsioHttpContext> SubmitRestQuery(const RestQueryProto& query) override;
  void Prepare();
  AsioHttpContextList SubmitRestQueryList(const RestQueryProto& query) override;
  RestParams GetRestOrderParams(const OrderSpec& order_spec, int64_t proc_order_id);
  RestParams GetRestCancelParams(const IOrderContext& order_context);

  std::string DebugString() const;

  void SetBullet(const std::string& channel, void* data);

  std::shared_ptr<AsioHttpContext> QueryTransfers(const RestParams& params);

 private:
  int64_t start_time_;
  std::unordered_map<std::string, int32_t> api_block_info_;
  std::unordered_map<std::string, int32_t> api_req_info_;
  KucoinRateTracker* local_rate_tracker_ = nullptr;
  bool is_bullet_ready_{false};
};
